﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using FinosLibrary;
using System.IO;
namespace FinosServiceLibrary.Server {
    public class Lobby {
        private static TcpListener listener;
        private static TcpListener adminListener;
        public static void open() {
            try {
                adminListener = new TcpListener(IPAddress.Any, 4501);
                adminListener.Start();
                ThreadPool.QueueUserWorkItem(new WaitCallback(acceptAdmin));
            } catch (Exception) {
            }
            try {
                string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "PolicyFile.xml";
                Policy.policyBytes = File.ReadAllBytes(path);
                ThreadPool.QueueUserWorkItem(new WaitCallback(Policy.PolicyThread));
                listener = new TcpListener(IPAddress.Any, 4502);
                listener.Start();
                Logger.warning("服务启动成功!");
                while (true) {
                    TcpClient connection = listener.AcceptTcpClient();
                    Logger.trace("Connect:" + connection.Client.RemoteEndPoint.ToString());
                    Client lc = new Client() { stream = connection.GetStream(), remoteEndPoint=connection.Client.RemoteEndPoint };
                    ThreadPool.QueueUserWorkItem(new WaitCallback(lc.WaitForSendData));
                }
            } catch (Exception e) {
                Logger.error(e.Message);
                Console.Read();
            }
        }
        public static void acceptAdmin(object stateInfo) {
            App adminApp = new App();
            adminApp.loadApp<AdminLogic>();
            while (true) {
                TcpClient connection = adminListener.AcceptTcpClient();
                Logger.trace("ConnectAdmin:" + connection.Client.RemoteEndPoint.ToString());
                ThreadPool.QueueUserWorkItem(new WaitCallback(new AdminClient() { stream = connection.GetStream(), remoteEndPoint = connection.Client.RemoteEndPoint, appBelong = adminApp.loader }.WaitForSendData));
            }
        }
    }
}
